#!/bin/bash

# 尝试卸载分区
sudo umount /dev/mmcblk0p8
sudo umount /dev/mmcblk0p7
sudo umount /dev/mmcblk0p6

# 删除自动挂载SD卡的udev规则
cmd echo "mount -o rw,remount / ; steamos-readonly disable; rm /usr/lib/udev/rules.d/99-sdcard-mount.rules" | steamos-chroot --disk /dev/mmcblk0 --partset A --

cmd echo "mount -o rw,remount / ; steamos-readonly disable; rm /usr/lib/udev/rules.d/99-sdcard-mount.rules" | steamos-chroot --disk /dev/mmcblk0 --partset B --

echo Start to insert script!

# 挂载home分区，如果不存在则创建deck的home目录和.repair目录
sudo mkdir -p /run/media/home
sudo mount /dev/mmcblk0p8 /run/media/home
sudo mkdir -p /run/media/home/deck/ &>/dev/null
sudo mkdir -p /run/media/home/deck/.repair &>/dev/null
sudo chown deck:deck /run/media/home/deck
sudo chown deck:deck /run/media/home/deck/.repair

# 将repair_install_sdcard.sh复制到.repair目录
FILE=/run/media/home/deck/.repair/repair_install_sdcard.sh
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
sudo cp "$SCRIPT_DIR/repair_install_sdcard.sh" $FILE
sudo chmod +x $FILE
sudo chown deck:deck $FILE

# 在SteamDeck操作系统的.profile文件中添加一行，以便在每次SteamDeck启动且deck用户登录时运行repair_install_sdcard.sh脚本
# 这确保用户无需手动运行repair_install_sdcard.sh脚本，特别是在全新安装过程中欢迎界面自动更新之前无法访问桌面控制台的情况下
cat >/run/media/home/deck/.profile <<EOF
~/.repair/repair_install_sdcard.sh
EOF

sudo umount /run/media/home

echo "Done!"
